package fr.alesia.deepstack.io.impl;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

import fr.alesia.deepstack.bean.Player;
import fr.alesia.deepstack.bean.Ranking;
import fr.alesia.deepstack.bean.Tournament;
import fr.alesia.deepstack.factory.BeanFactory;
import fr.alesia.deepstack.io.BeanReader;

public class RankingReader implements BeanReader<Ranking> {

	private static BeanReader<Ranking> instance = null;
	
	private RankingReader(){}
	
	public static BeanReader<Ranking> getInstance(){
		if(instance == null){
			instance = new RankingReader();
		}
		return instance;
	}
	
	public Ranking read(String line) {
		
		String[] tokens = line.split(",");
		if(tokens.length == 3){
			
			String playerId = "k" + tokens[1];
			String tournamentId = "k" + tokens[0];
			Integer rank = Integer.parseInt(tokens[2]);
			User user = UserServiceFactory.getUserService().getCurrentUser();
			
			Player player = BeanFactory.createPlayer(null, user);
			player.setId(playerId);
			
			Tournament tournament = BeanFactory.createTournament(null);
			tournament.setId(tournamentId);
			
			Ranking ranking = BeanFactory.createRanking(
				player,
				tournament,
				rank
			);

			user = null;
			player = null;
			tournament = null;
			
			return ranking;
		}
		else{
			return null;
		}
	}
}
